package com.springBoot.utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

/**
 * @author chenkuan
 * @version v1.0
 * @desc AES对称算法加密/解密工具类
 * @date 20/8/4 004 12:55
 */
public class AESUtil {
	/**
	 * 加密/解密算法名称
	 */
	private static final String ALGORITHM = "AES";

	/**
	 * 随机数生成器（RNG）算法名称
	 */
	private static final String RNG_ALGORITHM = "SHA1PRNG";

	/**
	 * 编码
	 */
	private static final String CHARSET_NAME = "UTF-8";

	/**
	 * 加密
	 */
	public static String encrypt(String content, String key) throws Exception {
		if (content == null || content.length() < 1) {
			return null;
		}
		KeyGenerator kgen = KeyGenerator.getInstance(ALGORITHM);
		SecureRandom random = SecureRandom.getInstance(RNG_ALGORITHM);
		random.setSeed(key.getBytes());
		kgen.init(128, random);
		SecretKey secretKey = kgen.generateKey();
		byte[] enCodeFormat = secretKey.getEncoded();
		SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, ALGORITHM);
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		byte[] byteContent = content.getBytes(CHARSET_NAME);
		cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
		byte[] byteRresult = cipher.doFinal(byteContent);
		StringBuilder sb = new StringBuilder();
		for (byte b : byteRresult) {
			String hex = Integer.toHexString(b & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

	/**
	 * 解密
	 */
	public static String decrypt(String content, String key) throws Exception {
		if (content == null || content.length() < 1) {
			return null;
		}
		if (content.trim().length() < 19) {
			return content;
		}
		byte[] byteRresult = new byte[content.length() / 2];
		for (int i = 0; i < content.length() / 2; i++) {
			int high = Integer.parseInt(content.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(content.substring(i * 2 + 1, i * 2 + 2), 16);
			byteRresult[i] = (byte) (high * 16 + low);
		}
		KeyGenerator kgen = KeyGenerator.getInstance(ALGORITHM);
		SecureRandom random = SecureRandom.getInstance(RNG_ALGORITHM);
		random.setSeed(key.getBytes());
		kgen.init(128, random);
		SecretKey secretKey = kgen.generateKey();
		byte[] enCodeFormat = secretKey.getEncoded();
		SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, ALGORITHM);
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
		byte[] result = cipher.doFinal(byteRresult);
		return new String(result);
	}
}